﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using RotovapPlatform.UI.ViewModels.MaterialManagement;
using Microsoft.Extensions.DependencyInjection;
using System.ComponentModel;
using System.Windows.Media;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Threading;
using System.Threading.Tasks;

namespace RotovapPlatform.UI.Views.MaterialManagement
{
	/// <summary>
	/// ShelfView.xaml 的交互逻辑
	/// </summary>
	public partial class ShelfView : UserControl
	{
		// 添加Command依赖属性
		public static readonly DependencyProperty CommandProperty =
			DependencyProperty.Register("Command", typeof(ICommand), typeof(ShelfView), new PropertyMetadata(null));

		// 添加静态标志位，防止递归调用
		private static bool _isRefreshing = false;

		private DispatcherTimer _debounceTimer;

		public ICommand Command
		{
			get { return (ICommand)GetValue(CommandProperty); }
			set { SetValue(CommandProperty, value); }
		}

		public ShelfView()
		{
			InitializeComponent();

			// 如果在设计时，创建一个设计时数据
			if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
			{
				// 使用设计时数据
				DataContext = new ShelfViewModel(null);
			}

			// 订阅DataContext变更事件
			this.DataContextChanged += ShelfView_DataContextChanged;

			// 订阅Loaded事件，确保在控件加载完成后刷新UI
			this.Loaded += (s, e) => ForceRefreshUI();
		}

		/// <summary>
		/// 公共方法，用于强制刷新UI
		/// </summary>
		public void ForceRefreshUI()
		{
			// 防止递归调用，避免StackOverflowException
			if (_isRefreshing)
			{
				Debug.WriteLine("ShelfView: 检测到递归调用，跳过当前刷新操作");
				return;
			}

			try
			{
				_isRefreshing = true;
				Debug.WriteLine("ShelfView: 开始强制刷新UI");

				// 使用批处理模式，减少布局更新次数
				using (var deferRefresh = Dispatcher.DisableProcessing())
				{
					// 刷新所有ItemsControl，确保普通货位能正确更新
					int refreshedCount = 0;
					RefreshAllItemsControls(this, ref refreshedCount);
					Debug.WriteLine($"ShelfView: 已刷新 {refreshedCount} 个ItemsControl");

					// 如果DataContext是ShelfViewModel，记录日志
					if (DataContext is ShelfViewModel viewModel)
					{
						Debug.WriteLine($"ShelfView: 刷新ShelfViewModel，共有 {viewModel.OccupiedSlots.Count} 个已占用槽位");
					}
				}

				Debug.WriteLine("ShelfView: 强制刷新UI完成");
			}
			finally
			{
				_isRefreshing = false;
			}
		}

		/// <summary>
		/// 刷新所有ItemsControl，确保普通货位能正确更新
		/// </summary>
		private void RefreshAllItemsControls(DependencyObject parent, ref int refreshedCount)
		{
			int count = VisualTreeHelper.GetChildrenCount(parent);

			for (int i = 0; i < count; i++)
			{
				var child = VisualTreeHelper.GetChild(parent, i);

				if (child is FrameworkElement element)
				{
					// 刷新ItemsControl
					if (element is ItemsControl itemsControl && itemsControl.ItemsSource != null)
					{
						Debug.WriteLine($"ShelfView: 刷新ItemsControl");
						itemsControl.Items.Refresh();

						refreshedCount++;
					}

					// 递归处理子元素
					RefreshAllItemsControls(child, ref refreshedCount);
				}
			}
		}

		/// <summary>
		/// 只刷新特殊位置的控件，提高性能
		/// </summary>
		public void RefreshSpecialPositions()
		{
			Debug.WriteLine("ShelfView: 开始刷新特殊位置");

			// 查找所有ItemsControl，刷新特殊位置的ItemsControl
			var itemsControls = FindVisualChildren<ItemsControl>(this);

			foreach (var itemsControl in itemsControls)
			{
				if (DataContext is ShelfViewModel viewModel)
				{
					// 检查是否是特殊位置的ItemsControl
					if (itemsControl.ItemsSource == viewModel.SecondShelfSpecialItems ||
						itemsControl.ItemsSource == viewModel.ThirdShelfSpecialItems)
					{
						Debug.WriteLine($"ShelfView: 刷新特殊位置ItemsControl");
						itemsControl.Items.Refresh();
					}
				}
			}
		}

		/// <summary>
		/// 查找指定类型的所有可视子元素
		/// </summary>
		private IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) where T : DependencyObject
		{
			int count = VisualTreeHelper.GetChildrenCount(parent);
			for (int i = 0; i < count; i++)
			{
				var child = VisualTreeHelper.GetChild(parent, i);
				if (child is T typedChild)
				{
					yield return typedChild;
				}

				foreach (var grandChild in FindVisualChildren<T>(child))
				{
					yield return grandChild;
				}
			}
		}

		private void ShelfView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
		{
			Debug.WriteLine("ShelfView: DataContext已变更");

			// 取消旧的DataContext的PropertyChanged事件订阅
			if (e.OldValue is INotifyPropertyChanged oldViewModel)
			{
				oldViewModel.PropertyChanged -= ViewModel_PropertyChanged;
			}

			// 订阅新的DataContext的PropertyChanged事件
			if (e.NewValue is INotifyPropertyChanged newViewModel)
			{
				newViewModel.PropertyChanged += ViewModel_PropertyChanged;

				// 如果是ShelfViewModel，立即刷新UI
				if (newViewModel is ShelfViewModel)
				{
					ForceRefreshUI();
				}
			}
		}

		private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			// 如果正在刷新中，不再触发新的刷新，避免递归调用
			if (_isRefreshing)
			{
				Debug.WriteLine($"ShelfView: 属性 {e.PropertyName} 已变更，但由于正在刷新中，跳过此次刷新");
				return;
			}

			// 使用防抖动机制，避免短时间内多次刷新
			// 当多个属性几乎同时变更时，只执行最后一次刷新
			if (_debounceTimer != null)
			{
				_debounceTimer.Stop();
				_debounceTimer = null;
			}

			// 当关键属性变更时，延迟刷新UI
			if (e.PropertyName == nameof(ShelfViewModel.TopShelfItems) ||
				e.PropertyName == nameof(ShelfViewModel.SecondShelfItems) ||
				e.PropertyName == nameof(ShelfViewModel.ThirdShelfItems) ||
				e.PropertyName == nameof(ShelfViewModel.BottomShelfItems) ||
				e.PropertyName == nameof(ShelfViewModel.SecondShelfSpecialItems) ||
				e.PropertyName == nameof(ShelfViewModel.ThirdShelfSpecialItems) ||
				e.PropertyName == nameof(ShelfViewModel.OccupiedSlots) ||
				e.PropertyName == nameof(ShelfViewModel.Slots))
			{
				Debug.WriteLine($"ShelfView: 属性 {e.PropertyName} 已变更，计划刷新UI");

				// 创建一个定时器，延迟50毫秒后执行刷新
				_debounceTimer = new System.Windows.Threading.DispatcherTimer();
				_debounceTimer.Interval = TimeSpan.FromMilliseconds(50);
				_debounceTimer.Tick += (s, args) =>
				{
					_debounceTimer.Stop();
					_debounceTimer = null;

					Debug.WriteLine($"ShelfView: 执行延迟的UI刷新");
					ForceRefreshUI();
				};
				_debounceTimer.Start();
			}
		}

		private void RefreshAllChildren(DependencyObject parent)
		{
			int count = VisualTreeHelper.GetChildrenCount(parent);

			for (int i = 0; i < count; i++)
			{
				var child = VisualTreeHelper.GetChild(parent, i);

				if (child is FrameworkElement element)
				{
					// 只对特定类型的控件进行刷新，减少不必要的刷新操作
					bool needsRefresh = false;

					// 特别处理ContentControl，确保特殊位置的瓶子能正确刷新
					if (element is ContentControl contentControl)
					{
						// 特殊处理带有Tag的ContentControl（特殊位置）
						if (element.Tag != null && (element.Tag.ToString().StartsWith("SecondShelfSpecial_") ||
												   element.Tag.ToString().StartsWith("ThirdShelfSpecial_")))
						{
							Debug.WriteLine($"ShelfView: 刷新特殊位置 {element.Tag}");

							// 强制刷新ContentControl的内容，但避免多次UpdateLayout
							var temp = contentControl.Content;
							contentControl.Content = null;
							contentControl.Content = temp;

							// 已经处理过这个元素，不需要再递归处理其子元素
							continue;
						}
						// 如果ContentControl的内容是ShelfSlotViewModel，强制刷新其绑定
						else if (contentControl.Content is ShelfSlotViewModel)
						{
							// 触发ContentControl的ContentChanged事件
							var temp = contentControl.Content;
							contentControl.Content = null;
							contentControl.Content = temp;

							// 已经处理过这个元素，不需要再递归处理其子元素
							continue;
						}

						needsRefresh = true;
					}
					else if (element is ItemsControl)
					{
						// 对ItemsControl进行刷新
						((ItemsControl)element).Items.Refresh();
						needsRefresh = true;
					}
					else if (element is Panel)
					{
						// 对Panel进行刷新
						needsRefresh = true;
					}

					// 只对需要刷新的元素进行InvalidateVisual
					if (needsRefresh)
					{
						element.InvalidateVisual();
					}

					// 递归处理子元素，但只处理可能包含特殊位置的容器
					if (element is Panel || element is ItemsControl)
					{
						RefreshAllChildren(child);
					}
				}
			}
		}

		private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			ShelfSlotViewModel slot = null;

			// 获取点击的槽位
			if (sender is FrameworkElement element)
			{
				// 处理特殊位置
				if (element.Tag != null)
				{
					string tag = element.Tag.ToString();

					// 处理第二层特殊位置
					if (tag.StartsWith("SecondShelfSpecial_"))
					{
						int index = int.Parse(tag.Split('_')[1]);
						if (DataContext is ShelfViewModel viewModel)
						{
							slot = viewModel.SecondShelfSpecialItems[index];
						}
					}
					// 处理第三层特殊位置
					else if (tag.StartsWith("ThirdShelfSpecial_"))
					{
						int index = int.Parse(tag.Split('_')[1]);
						if (DataContext is ShelfViewModel viewModel)
						{
							slot = viewModel.ThirdShelfSpecialItems[index];
						}
					}
					// 处理新的特殊位置标记格式
					else if (tag == "0" && element.Parent is FrameworkElement parentElement &&
							parentElement.Parent is ContentPresenter contentPresenter &&
							contentPresenter.Parent is Panel panel &&
							panel.Parent is ItemsControl itemsControl)
					{
						// 获取ItemsControl的ItemsSource
						if (itemsControl.ItemsSource is IEnumerable<ShelfSlotViewModel> slots &&
							DataContext is ShelfViewModel viewModel)
						{
							// 获取当前项的索引
							int index = contentPresenter.GetValue(ItemsControl.AlternationIndexProperty) as int? ?? 0;

							// 根据ItemsControl确定是哪个特殊位置集合
							if (itemsControl.ItemsSource == viewModel.SecondShelfSpecialItems)
							{
								slot = viewModel.SecondShelfSpecialItems[index];
							}
							else if (itemsControl.ItemsSource == viewModel.ThirdShelfSpecialItems)
							{
								slot = viewModel.ThirdShelfSpecialItems[index];
							}
						}
					}
				}
				// 处理普通位置
				if (slot == null && element.DataContext is ShelfSlotViewModel slotViewModel)
				{
					slot = slotViewModel;
				}
			}

			// 设置选中状态
			if (slot != null)
			{
				Debug.WriteLine($"ShelfView: 选中了槽位 {slot.DisplayPosition}，占用状态: {slot.IsOccupied}，Layer={slot.Layer}, Position={slot.Position}");

				if (slot.IsOccupied && slot.Bottle != null)
				{
					Debug.WriteLine($"ShelfView: 槽位 {slot.DisplayPosition} 的瓶子信息 - 类型: {slot.Bottle.Type}, 功能: {slot.Bottle.Function}");
				}

				// 如果是ShelfViewModel，设置其SelectedSlot
				if (DataContext is ShelfViewModel viewModel)
				{
					// 清除所有选中状态
					ClearAllSelections(viewModel);

					slot.IsSelected = true;
					viewModel.SelectedSlot = slot;

					Debug.WriteLine($"ShelfView: 已设置 SelectedSlot = {viewModel.SelectedSlot.DisplayPosition}");
				}

				// 执行外部命令
				if (Command != null && Command.CanExecute(slot))
				{
					Command.Execute(slot);
				}
			}
		}

		private void ClearAllSelections(ShelfViewModel viewModel)
		{
			foreach (var slot in viewModel.TopShelfItems)
				slot.IsSelected = false;

			foreach (var slot in viewModel.SecondShelfItems)
				slot.IsSelected = false;

			foreach (var slot in viewModel.ThirdShelfItems)
				slot.IsSelected = false;

			foreach (var slot in viewModel.BottomShelfItems)
				slot.IsSelected = false;

			foreach (var slot in viewModel.SecondShelfSpecialItems)
				slot.IsSelected = false;

			foreach (var slot in viewModel.ThirdShelfSpecialItems)
				slot.IsSelected = false;
		}
	}
}